<?php

namespace app\store\model;

use app\common\model\User as UserModel;

use app\common\service\Order as OrderService;
use app\store\model\dealer\User as DealerUserModel;
use app\store\model\user\GradeLog as GradeLogModel;
use app\store\model\user\PointsLog as PointsLogModel;
use app\store\model\user\BalanceLog as BalanceLogModel;
use app\store\model\user\MoneyLog as MoneyLogModel;
use app\common\enum\user\moneylog\Scene as SceneEnum;
use app\common\enum\user\pointsLog\Scene as PointsSceneEnum;
use app\common\enum\user\grade\log\ChangeType as ChangeTypeEnum;
use app\api\model\dealer\Referee as RefereeModel;
use app\common\library\helper;
use app\common\library\MysicLog;
use utils\Services;
use app\factory\MqFactory;

/**
 * 用户模型
 * Class User
 * @package app\store\model
 */
class User extends UserModel
{


    /**
     * 获取当前用户总数
     * @param null $day
     * @return int|string
     * @throws \think\Exception
     */
    public function getUserTotal($day = null)
    {
        if (!is_null($day)) {
            $startTime = strtotime($day);
            $this->where('create_time', '>=', $startTime)
                ->where('create_time', '<', $startTime + 86400);
        }
        return $this->where('is_delete', '=', '0')->count();
    }

    /**
     * 获取用户列表
     * @param string $nickName 昵称
     * @param int $gender 性别
     * @param int $grade 会员等级
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($nickName = '', $gender = -1, $grade = null ,$deacler = null,$staff = null)
    {

        // 检索：微信昵称
        !empty($nickName) && $this->where('nickName', 'like', "%$nickName%");
        // 检索：性别
        if ($gender !== '' && $gender > -1) {
            $this->where('gender', '=', (int)$gender);
        }
        // 检索：会员等级
        $grade > 0 && $this->where('grade_id', '=', (int)$grade);
        // 检索：分销权限
        $deacler > -1 && $this->where('deacler', '=', (int)$deacler);
        // 检索：是否代言人
        $staff > -1 && $this->where('is_staff', '=', (int)$staff);
        // 获取用户列表
        $list = $this->with(['grade'])
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ])->each(function($item,$key){
                if($item['vip_level']){
                    $item['vip_name'] = db('wxapp_card')->where(['card_id'=>$item['vip_level']])
                        ->value('card_title');
                }else{
                    $item['vip_name'] = "--";
                }
                $item['wxapp_money'] = db('wxapp')->where(['wxapp_id'=>self::$wxapp_id])
                    ->value('money');
                return $item;
            });
        return $list;
    }

    /**
     * 删除用户
     * @return bool|mixed
     */
    public function setDelete()
    {
        // 判断是否为分销商
        if (DealerUserModel::isDealerUser($this['user_id'])) {
            $this->error = '当前用户为分销商，不可删除';
            return false;
        }
        return $this->transaction(function () {
            // 删除用户推荐关系
            (new DealerUserModel)->onDeleteReferee($this['user_id']);
            // 标记为已删除
            return $this->save(['is_delete' => 1]);
        });
    }




    /**
     * 用户充值
     * @param string $storeUser 当前操作人
     * @param array $data post数据
     * @return bool
     */
    public function recharge($storeUser, $data)
    {

        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '用户充值');

        // 更新记录
        $this->startTrans();
        try {
            if (!isset($data['money']) || $data['money'] === '' || $data['money'] < 0) {
                $log->info($data['money'], '充值金额');
                $log->info("充值金额不正确", '充值金额不正确');
                $this->error = '请输入正确的金额';
                return false;
            }

            if ($data['money'] < 100) {
                $log->info($data['money'], '充值金额');
                $log->info("充值金额不正确", '充值金额不正确');
                $this->error = '最低充值金额为100';
                return false;
            }

            //商户当前额度
            $wxapp_money = db('wxapp')->where(['wxapp_id'=>$this['wxapp_id']])->value('money');

            $log->info($wxapp_money, '商户当前额度');

            if ($wxapp_money < $data['money']) {
                $log->info("当前额度不足", '当前额度不足');
                $this->error = '当前额度不足';
                return false;
            }

            //商户操作逻辑
            $this->wxappMoney($storeUser, $data);
            //用户操作逻辑
            $this->userMoney($storeUser, $data);
            //服务商分账
            $this->setOperateCenterAccounts($data);
            //生成订单
            $order_id = $this->creatOrder($data['money']);
            //分销处理
            $this->updateDealer($data,$order_id);
            //实际分账接收方记录主表（用户）
            $this->addDivideReceives($order_id);

            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $log->info($e->getMessage(), '用户充值抛出异常');
            $this->rollback();

            return false;

        }


    }


    /**
     * 实际分账接收方记录主表
     * @param string $storeUser 当前操作人用户名
     * @param array $data post数据
     * @return bool
     */
    public function addDivideReceives($order_id){


        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '加入实际分账接收方记录主表');

        //查找订单
        $orderInfo = db('large_order_log')->find($order_id);

        //查找用户open_id
        $open_id = db('user')->where(['user_id'=>$this['user_id']])->value('open_id');

        $time = time();

        //查找分红配置
        $bonusSettingEntity = db('wxapp_setting')->where('wxapp_id', $this['wxapp_id'])->find();

        if(!$bonusSettingEntity) {
            $log->info("分红设置为空", '获取商户的分红设置结果');
            return false;
        }
        $log->info($bonusSettingEntity['status'], '分红状态');
        $log->info($bonusSettingEntity['start_time'], '开始时间');
        $log->info($bonusSettingEntity['term'], '分红周期');
        $log->info($bonusSettingEntity['money'], '分红条件');
        $log->info($bonusSettingEntity['upline'], '分红上限');
        $log->info($bonusSettingEntity['rewardpercent'], '商户分红拨比');
        $issue = $bonusSettingEntity['periods_num'] ?? 0;
        $log->info($issue, '分红期号');


        //活动设置不存在 |  活动未开始 | 活动已关闭  | 订单金额未达到参与活动最低金额， 本订单用户身份不更新为微股东,不分红
        if(!$bonusSettingEntity || $bonusSettingEntity['start_time'] > $time || $bonusSettingEntity['status'] != 1  || $orderInfo['pay_price'] < $bonusSettingEntity['money']){

            $logData = [
                '活动设置是否存在' => bool2str(isset($bonusSettingEntity)),
                '活动未开始' => bool2str($bonusSettingEntity['start_time'] > $time),
                '活动已关闭' => bool2str($bonusSettingEntity['status'] != 1),
                '订单金额未达到参与活动最低金额' => bool2str($orderInfo['pay_price'] < $bonusSettingEntity['money'])
            ];

            $log->info($logData, '条件判断结果');
            return false;
        }

        //计算本次分红的分红上限 分红金额
        $bonusUpperLimit = bcmul(strval($orderInfo['pay_price']), bcdiv(strval($bonusSettingEntity['upline']), '100',2),2);

        //额度流水表加记录
        $data = [
            'user_id' => $this['user_id'],//用户id
            'account' => $open_id,//用户openid
            'order_no' => $orderInfo['order_no'],//订单号
            'wxapp_id' => $this['wxapp_id'],//微信小程序内部编号
            'payment' => $orderInfo['pay_price'],//实际支付总金额
            'periods_num' => $issue,//期号
            'transaction_id' => 'large'.OrderService::createOrderNo(),//微信内部订单
            'balance' => $bonusUpperLimit,//本条订单剩余金额
            'top_limit' => $bonusUpperLimit,//分红上限
            'total_abonus' => 0,//累计分红额
            'type' => 0,//是否参与分红（0，参与，1.不参与）
            'times' => 0,//退款次数
            'create_time' => time(),//写入时间
            'update_time' => time(),//更新时间
            'reward_money' => 0,//累计分红赏金
            'refund_money' => 0,//累计分红退款
            'finish_time' => $time + intval($bonusSettingEntity['term']) * 24 * 60 * 60,//结束分账时间
            'small_change' => 0,//出局余额零钱
            'is_large' => 2,//是否是大额支付 1 普通 2 大额支付

        ];

        $log_id = db('divide_receives')->insertGetId($data);

        $log->info($log_id, '加入实际分账接收方记录主表结果');


    }


    /**
     * 商户操作逻辑
     * @param string $storeUser 当前操作人用户名
     * @param array $data post数据
     * @return bool
     */
    public function wxappMoney($storeUser, $data){


        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '商户额度操作开始');

        //减少额度
        db('wxapp')->where(['wxapp_id'=>$this['wxapp_id']])->setDec('money',$data['money']);
        $log->info("成功", '减少额度');

        //额度流水表加记录
        $log_money = [
            'money' => -$data['money'],
            'wxapp_id' => $this['wxapp_id'],
            'create_time' => time(),
            'user_id' => $this['user_id'],
            'store_user_id' =>  $storeUser['store_user_id'],
            'type' => 2,
        ];
        $log->info($log_money, '额度流水表加入数据');
        $log_id = db('large_log')->insertGetId($log_money);
        $log->info($log_id, '额度流水表加入结果');


    }



    /**
     * 用户操作逻辑
     * @param string $storeUser 当前操作人用户名
     * @param array $data post数据
     * @return bool
     */
    public function userMoney($storeUser, $data){


        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '用户操作余额操作开始');

        //增加用户零钱
        db('user')->where(['user_id'=>$this['user_id']])->setInc('money',$data['money']);
        $log->info("成功", '增加用户零钱');
        //增加用户总支付金额
        db('user')->where(['user_id'=>$this['user_id']])->setInc('pay_money',$data['money']);
        $log->info("成功", '增加用户总支付金额');
        //将用户设置为微股东
        db('user')->where(['user_id'=>$this['user_id']])->update(['shareholder'=>1]);
        $log->info("成功", '将用户设置为微股东');
        //用户单笔支付表加记录
        $this->singleOrder($data['money']);
        $log->info("成功", '用户单笔支付表加记录');
        //用户零钱流水表加记录
        $log_money = [
            'user_id' => $this['user_id'],
            'scene' => 40,
            'money' => $data['money'],
            'remark' => $data['remark'],
            'wxapp_id' =>  $this['wxapp_id'],
            'create_time' => time(),
        ];
        $log->info($log_money, '用户零钱流水表加入数据');
        $log_id = db('user_money_log')->insertGetId($log_money);
        $log->info($log_id, '用户零钱流水表加入数据结果');


    }

    /**
     * 用户单条订单记录表
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */

    private  function singleOrder($money){
        //分销商表
        $order = db('single_order')->where(['user_id'=>$this['user_id'],'wxapp_id'=>$this['wxapp_id']])->find();
        if(!$order){
            $single_data = [
                'amount'=>$money,
                'wxapp_id'=>$this['wxapp_id'],
                'pay_type'=>20,
                'user_id'=>$this['user_id'],
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            db('single_order')->insertGetId($single_data);
        }else{
            if($order['amount']<$money){
                $data['update_time'] = time();
                db('single_order')
                    ->where(['user_id'=>$this['user_id'],'wxapp_id'=>$this['wxapp_id']])
                    ->update(['amount'=>$money]);
            }
        }
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setOperateCenterAccounts($payData){


        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '服务商分账');

        $agentId = db ('wxapp')->where(['wxapp_id'=>$this['wxapp_id']])->value('agent_id');
        $log->info($agentId, '服务商ID');

        $money = bcmul($payData['money'],0.01,2);

        if ($agentId!==0){
            $agentList = collection(
                db('agent')
                    ->where(['is_recycle'=>0,'status'=>1,'is_delete'=>0])
                    ->order('agent_id desc')->select()
            )->toArray();//合伙人层级

            if (!empty($agentList)){
                $tree = Services::instance();
                $tree->init($agentList, 'recommend_id');
                $agentData = $tree->getParents($agentId,true);

                $agentCount = count($agentData);

                $agentDividendsDataArray = [];

                if($agentCount==1){//服务商
                    $agentDividendsDataArray['name']          = $agentData[0]['company_name'];
                    $agentDividendsDataArray['type']          = 1;
                    $agentDividendsDataArray['agent_id']      = $agentData[0]['agent_id'];
                    $agentDividendsDataArray['amount']        = bcmul(($agentData[0]['service_charge']/100),($money*0.01),4);

                    $agentDividendsDataArray['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray['order_no']      = '';//订单号
                    $agentDividendsDataArray['payment']       = $money;//订单实际支付金额
                    $agentDividendsDataArray['transaction_id']= '';
                    $agentDividendsDataArray['wxapp_id']      = $this['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray['status']        = 1;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray['update_time']   = time();//写入时间（支付时间）
                    db('divide_service')->insert($agentDividendsDataArray);
                }elseif ($agentCount==2){
                    $agentDividendsDataArray[0]['name']          = $agentData[0]['company_name'];
                    $agentDividendsDataArray[0]['type']          = 1;
                    $agentDividendsDataArray[0]['agent_id']      = $agentData[0]['agent_id'];
                    $agentDividendsDataArray[0]['amount']        = bcmul((($agentData[0]['service_charge']-$agentData[1]['service_charge'])/100),bcmul($money,0.01,4),4);
                    $agentDividendsDataArray[0]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray[0]['order_no']      = '';//订单号
                    $agentDividendsDataArray[0]['payment']       = $money;//订单实际支付金额
                    $agentDividendsDataArray[0]['transaction_id']= '';
                    $agentDividendsDataArray[0]['wxapp_id']      = $this['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[0]['status']        = 1;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[0]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[0]['update_time']   = time();//写入时间（支付时间）
                    if($agentData[1]['type']==1){
                        //分账给运营商
                        $agentDividendsDataArray[1]['name']          = $agentData[1]['company_name'] ? $agentData[1]['company_name'] : $agentData[1]['real_name'];
                        $agentDividendsDataArray[1]['type']          = 2;
                        $agentDividendsDataArray[1]['agent_id']      = $agentData[1]['agent_id'];
                        $agentDividendsDataArray[1]['amount']        = bcmul(($agentData[1]['service_charge']/100),bcmul($money,0.01,4),4);
                        $agentDividendsDataArray[1]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                        $agentDividendsDataArray[1]['order_no']      = '';//订单号
                        $agentDividendsDataArray[1]['payment']       = $money;//订单实际支付金额
                        $agentDividendsDataArray[1]['transaction_id']= '';
                        $agentDividendsDataArray[1]['wxapp_id']      = $this['wxapp_id'];//内部微信小程序编号
                        $agentDividendsDataArray[1]['status']        = 1;//状态（0，未分账，1.已分账，2.分账失败）
                        $agentDividendsDataArray[1]['create_time']   = time();//写入时间（支付时间）
                        $agentDividendsDataArray[1]['update_time']   = time();//写入时间（支付时间）
                    }elseif ($agentData[1]['type']==2){
                        //分账给合伙人
                        $agentDividendsDataArray[1]['name']          = $agentData[1]['real_name'];
                        $agentDividendsDataArray[1]['type']          = 3;
                        $agentDividendsDataArray[1]['agent_id']      = $agentData[1]['agent_id'];
                        $agentDividendsDataArray[1]['amount']        = bcmul(($agentData[1]['service_charge']/100),bcmul($money,0.01,4),4);
                        $agentDividendsDataArray[1]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                        $agentDividendsDataArray[1]['order_no']      = '';//订单号
                        $agentDividendsDataArray[1]['payment']       = $money;//订单实际支付金额
                        $agentDividendsDataArray[1]['transaction_id']= '';
                        $agentDividendsDataArray[1]['wxapp_id']      = $this['wxapp_id'];//内部微信小程序编号
                        $agentDividendsDataArray[1]['status']        = 1;//状态（0，未分账，1.已分账，2.分账失败）
                        $agentDividendsDataArray[1]['create_time']   = time();//写入时间（支付时间）
                        $agentDividendsDataArray[1]['update_time']   = time();//写入时间（支付时间）
                    }
                    db('divide_service')->insertAll($agentDividendsDataArray);

                }elseif($agentCount==3){
                    $agentDividendsDataArray[0]['name']          = $agentData[0]['company_name'];
                    $agentDividendsDataArray[0]['type']          = 1;
                    $agentDividendsDataArray[0]['agent_id']      = $agentData[0]['agent_id'];
                    $agentDividendsDataArray[0]['amount']        = bcmul((($agentData[0]['service_charge']-$agentData[1]['service_charge'])/100),bcmul($money,0.01,4),4);
                    $agentDividendsDataArray[0]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray[0]['order_no']      = '';//订单号
                    $agentDividendsDataArray[0]['payment']       = $money;//订单实际支付金额
                    $agentDividendsDataArray[0]['transaction_id']= '';
                    $agentDividendsDataArray[0]['wxapp_id']      = $this['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[0]['status']        = 1;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[0]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[0]['update_time']   = time();//写入时间（支付时间）

                    $agentDividendsDataArray[1]['name']          = $agentData[1]['company_name'] ? $agentData[1]['company_name'] : $agentData[1]['real_name'];
                    $agentDividendsDataArray[1]['type']          = 2;
                    $agentDividendsDataArray[1]['agent_id']      = $agentData[1]['agent_id'];
                    $agentDividendsDataArray[1]['amount']        = bcmul((($agentData[1]['service_charge']-$agentData[2]['service_charge'])/100),bcmul($money,0.01,4),4);
                    $agentDividendsDataArray[1]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray[1]['order_no']      = '';//订单号
                    $agentDividendsDataArray[1]['payment']       = $money;//订单实际支付金额
                    $agentDividendsDataArray[1]['transaction_id']= '';
                    $agentDividendsDataArray[1]['wxapp_id']      = $this['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[1]['status']        = 1;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[1]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[1]['update_time']   = time();//写入时间（支付时间）


                    $agentDividendsDataArray[2]['name']          = $agentData[2]['real_name'];
                    $agentDividendsDataArray[2]['type']          = 3;
                    $agentDividendsDataArray[2]['agent_id']      = $agentData[2]['agent_id'];
                    $agentDividendsDataArray[2]['amount']        = bcmul(($agentData[2]['service_charge']/100),bcmul($money,0.01,4),4);
                    $agentDividendsDataArray[2]['abonus']        = bcmul($money,0.01,2);//参与分账金额
                    $agentDividendsDataArray[2]['order_no']      = '';//订单号
                    $agentDividendsDataArray[2]['payment']       = $money;//订单实际支付金额
                    $agentDividendsDataArray[2]['transaction_id']= '';
                    $agentDividendsDataArray[2]['wxapp_id']      = $this['wxapp_id'];//内部微信小程序编号
                    $agentDividendsDataArray[2]['status']        = 1;//状态（0，未分账，1.已分账，2.分账失败）
                    $agentDividendsDataArray[2]['create_time']   = time();//写入时间（支付时间）
                    $agentDividendsDataArray[2]['update_time']   = time();//写入时间（支付时间）
                    db('divide_service')->insertAll($agentDividendsDataArray);
                }

            }
        }


    }



    /**
     * 分销处理
     * @param array|\think\Model $order 订单详情
     * @param int $orderType 订单类型
     * @return bool|false|int
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function updateDealer($data,$order_id)
    {

        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '分销处理开始');

        //获取分销方案
        $dealer_case = db('wxapp')->where(['wxapp_id'=>$this['wxapp_id']])->value('dealer_case');
        $log->info($dealer_case, '获取分销方案');

        //获取上级ID
        $refereeId = RefereeModel::isExistReferee($this['user_id']);
        $log->info($refereeId, '获取上级ID');

        if(!$refereeId){
            $log->info('没有上级', '没有上级');
            return false;
        }

        $refereeModel = new UserModel;
        //上级详情
        $refereeInfo = $refereeModel::detail($refereeId);
        if ($refereeInfo) {
            $userData = [
                'user_id' => $refereeInfo['user_id'],
                'nickName' => $refereeInfo['nickName'],
                'pay_money' => $refereeInfo['pay_money'],
                'shareholder' => $refereeInfo['shareholder'],
                'vip_level' => $refereeInfo['vip_level'],
                'is_staff' => $refereeInfo['is_staff'],
                'deacler' => $refereeInfo['deacler'],
            ];
            $log->info($userData, '上级详情');
        }

        //用户分销权限为禁用
        if($refereeInfo['deacler']==2){
            $log->info('用户分销权限为禁用', '用户分销权限为禁用');
            return false;
        }

        //如果为分销方案一
        if($dealer_case == 1){

            $log->info("开始", '查找对应金额的储值卡');
            //查找对应金额的会员卡
            $card = db('wxapp_card')
                ->where(['card_real_money'=>$data['money'],'wxapp_id'=>$this['wxapp_id'],'is_delete'=>0])
                ->find();

            $log->info($card?:[], '查找对应金额的储值卡结果');
            if(!$card){
                $log->info("未找到对应金额的储值卡", '未找到对应金额的储值卡');
                return false;
            }
            if($card['reward_percent']<=0){
                $log->info("储值卡赏金比例不满足条件", '储值卡赏金比例不满足条件');
                return false;
            }

            $checkDealer = $this->dealerOne($refereeInfo);
            if($checkDealer){
                $this->createDealerOrder($data['money'],$refereeId, $card['reward_percent'], $dealer_case,$order_id);
            }
        }

        if ($dealer_case == 2) {//分销方案二
            $checkDealer = $this->dealerTow($refereeInfo);
            if ($checkDealer) {
                //创建分销订单
                $this->createDealerOrder($data['money'],$refereeId, $checkDealer, $dealer_case,$order_id);

            }
        }



    }


    /**
     * 分销方案一处理
     * @param array|\think\Model $order 订单详情
     * @param int $orderType 订单类型
     * @return bool|false|int
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function dealerOne($refereeInfo){

        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '分销方案一处理开始');
        //获取当前分销方案一的配置
        $dealer_setting_one = db("distribution_setting")
            ->where(['wxapp_id' => $this['wxapp_id'], 'dealer_type' => 1])
            ->value('setting_content');
        $log->info($dealer_setting_one, '获取当前分销方案一的配置');

        if(!$dealer_setting_one){
            $log->info('分销方案一配置错误', '分销方案一配置错误');
            return false;
        }

        $oneCase = json_decode($dealer_setting_one,true);

        if($oneCase['status']==2 ){
            $log->info('分销方案一配置状态为关闭状态', '分销方案一配置状态为关闭状态');
            return false;
        }

        if($oneCase['card_status']==2 ){
            $log->info('分销方案一储值卡赏金为关闭状态', '分销方案一储值卡赏金为关闭状态');
            return false;
        }

        if($refereeInfo['deacler']==1){
            $log->info('用户分销权限为启用', '用户分销权限为启用');
            return true;
        }
        //单笔
        if($oneCase['distribution_type']==1){
            $log->info('单笔', '分销类型');
            $singleOrder = db('single_order')
                ->where(['wxapp_id'=>$this['wxapp_id'],'user_id'=>$refereeInfo['user_id']])
                ->find();
            $log->info($singleOrder, '用户单笔支付金额记录');

            if($singleOrder){
                if($singleOrder['amount']<$oneCase['distribution_con']){
                    $log->info('用户单笔支付金额记录不满足条件', '用户单笔支付金额记录不满足条件');
                    return false;
                }else{
                    return true;
                }
            }else{
                if($oneCase['distribution_con']>0){
                    $log->info('用户单笔支付金额记录不满足条件', '用户单笔支付金额记录不满足条件');
                    return false;
                }else{
                    return true;
                }
            }

        }elseif($oneCase['distribution_type']==2){//分销类型 累加
            $log->info('累加', '分销类型');
            if($refereeInfo['pay_money']<$oneCase['distribution_con']){
                $log->info('用户总支付金额记录不满足条件', '用户总支付金额记录不满足条件');
                return false;
            }
        }

        return true;

    }



    /**
     * 分销方案二处理
     * @param array|\think\Model $order 订单详情
     * @param int $orderType 订单类型
     * @return bool|false|int
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function dealerTow($refereeInfo){

        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '分销方案二处理开始');

        //获取分销方案二的配置信息
        $dealer_setting_tow = db("distribution_setting")
            ->where(['wxapp_id' => $this['wxapp_id'], 'dealer_type' => 2])
            ->value('setting_content');
        $log->info($dealer_setting_tow, '获取当前分销方案二的配置');

        if(!$dealer_setting_tow){
            $log->info('分销方案二配置错误', '分销方案二配置错误');
            return false;
        }

        $towCase = json_decode($dealer_setting_tow,true);

        //用户身份为代言人
        if($refereeInfo['is_staff']>0){
            $log->info('用户身份为代言人', '用户身份');
            if($towCase['staff']['card_status']!=1){
                $log->info('储值卡赏金状态关闭', '储值卡赏金状态关闭');
                return false;
            }

            if($towCase['staff']['dealer_percent']<=0 || !$towCase['staff']['dealer_percent']){
                $log->info('储值卡赏金比例或者状态不正确', '储值卡赏金比例或者状态不正确');
                return false;
            }

            return $towCase['staff']['dealer_percent'];

        }

        //用户身份为会员
        if($refereeInfo['vip_level']>0){
            $log->info('用户身份为会员', '用户身份');
            if($towCase['vip']['card_status']!=1){
                $log->info('储值卡赏金状态关闭', '储值卡赏金状态关闭');
                return false;
            }
            //根据用户等级查询对应的会员卡设置的分销比例
            $dealer_percent = db('wxapp_card')
                ->where(['card_id'=>$refereeInfo['vip_level'],'wxapp_id'=>$this['wxapp_id']])
                ->value('reward_percent');

            if(!$dealer_percent || $dealer_percent<=0){
                $log->info('储值卡赏金比例或者状态不正确', '储值卡赏金比例或者状态不正确');
                return false;
            }

            return $dealer_percent;

        }

        //用户身份为微股东
        if($refereeInfo['shareholder']==1){
            $log->info('用户身份为微股东', '用户身份');
            if($towCase['wgd']['card_status']!=1){
                $log->info('储值卡赏金状态关闭', '储值卡赏金状态关闭');
                return false;
            }
            if($towCase['wgd']['dealer_percent']<=0 || !$towCase['wgd']['dealer_percent']){
                $log->info('储值卡赏金比例或者状态不正确', '储值卡赏金比例或者状态不正确');
                return false;
            }
            return $towCase['wgd']['dealer_percent'];
        }

        //用户身份为普通会员
        if($refereeInfo['shareholder']==0){
            $log->info('用户身份为普通会员', '用户身份');
            if($towCase['common']['card_status']!=1) {
                $log->info('储值卡赏金状态关闭', '储值卡赏金状态关闭');
                return false;
            }
            if($towCase['common']['dealer_percent']<=0 || !$towCase['common']['dealer_percent']){
                $log->info('储值卡赏金比例或者状态不正确', '储值卡赏金比例或者状态不正确');
                return false;
            }
            return $towCase['common']['dealer_percent'];
        }



    }


    /**
     * 生成订单
     * @param array|\think\Model $order 订单详情
     * @param int $orderType 订单类型
     * @return bool|false|int
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function creatOrder($money){
        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '生成订单');
        $orderData = [
            'order_no' => OrderService::createOrderNo(),
            'pay_price' => $money,
            'pay_status' => 20,
            'pay_time' => time(),
            'order_status' => 30,
            'is_settled' =>1,
            'user_id' => $this['user_id'],
            'wxapp_id' => $this['wxapp_id'],
            'create_time' => time(),
            'update_time' => time(),
            'is_fictitious' => 1,
        ];
        $log->info($orderData, '生成订单数据');
        $order_id = db('large_order_log')->insertGetId($orderData);
        $log->info($order_id, '生成订单结果ID');
        return $order_id;

    }
    /**
     * 创建分销订单
     * @param $order
     * @param int $order_type
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public function createDealerOrder($money,$refereeId, $percent, $dealer_case,$order_id)
    {
        $log = MysicLog::instance();
        $log->setFilename('admin/large');
        $log->info("开始", '创建分销订单');

        //计算分销佣金
        $first_money = bcmul($percent/100, $money,2);
        $log->info($first_money, '分销金额');

        $dealer_order = [
            'user_id' => $this['user_id'],//用户id (买家)
            'order_id' => $order_id,//订单id
            'order_type' => 5,//订单类型(10商城订单 20拼团订单 30 购买vip 40 购买爆品礼 50 当面付 60分红转化 5大额支付)
            'order_price' => $money,//订单总金额
            'first_user_id' => $refereeId,//分销商用户id(一级)
            'second_user_id' => 0,//分销商用户id(二级)
            'third_user_id' => 0,//分销商用户id(三级)
            'first_money' => $first_money,//分销佣金(一级)
            'second_money' => 0,//分销佣金(二级)
            'third_money' => 0,//分销佣金(三级)
            'is_invalid' => 0,//订单是否失效(0未失效 1已失效)
            'is_settled' => 1,//是否已结算佣金(0未结算 1已结算)
            'settle_time' => time(),//结算时间
            'wxapp_id' => $this['wxapp_id'],//小程序id
            'create_time' => time(),//创建时间
            'update_time' => time(),//更新时间
            'dealer_case' =>  $dealer_case,//分销方案
        ];


        $log->info($dealer_order, '获取分销订单加入的数据');
        $dealer_order_id = db('dealer_order')->insertGetId($dealer_order);
        $log->info($dealer_order_id, '获取分销订单id');

        if($dealer_order_id){
            //分销商用户记录表
            db('dealer_user')->where(['user_id'=>$refereeId])->setInc('money', $first_money);
            //分销商资金明细表
            $capitalData = [
                'user_id'=>$refereeId,
                'flow_type'=>90,
                'money'=>$first_money,
                'wxapp_id'=>$this['wxapp_id'],
                'create_time'=>time(),
                'update_time'=>time(),
            ];

            $log->info($capitalData, '分销商资金明细表数据');
            $dealer_capital_id = db('dealer_capital')->insertGetId($capitalData);
            $log->info($dealer_capital_id, '分销商资金明细表ID');

        }

    }




    /**
     * 用户充值：积分
     * @param $storeUserName
     * @param $data
     * @return bool
     */
    private function rechargeToPoints($storeUserName, $data)
    {
        if (!isset($data['value']) || $data['value'] === '' || $data['value'] < 0) {
            $this->error = '请输入正确的积分数量';
            return false;
        }
        // 判断充值方式，计算最终积分
        if ($data['mode'] === 'inc') {
            $diffMoney = $data['value'];
        } elseif ($data['mode'] === 'dec') {
            $diffMoney = -$data['value'];
        } else {
            $diffMoney = $data['value'] - $this['points'];
        }
        // 更新记录
        $this->transaction(function () use ($storeUserName, $data, $diffMoney) {
            // 更新账户积分
            $this->setInc('points', $diffMoney);
            // 新增积分变动记录
            PointsLogModel::add([
                'scene'=>PointsSceneEnum::ADMIN,
                'user_id' => $this['user_id'],
                'value' => $diffMoney,
                'describe' => "后台管理员 [{$storeUserName}] 操作",
                'remark' => $data['remark'],
            ]);
        });
        return true;
    }

    /**
     * 修改用户等级
     * @param $data
     * @return mixed
     */
    public function updateGrade($data)
    {
        // 变更前的等级id
        $oldGradeId = $this['grade_id'];
        return $this->transaction(function () use ($oldGradeId, $data) {
            // 更新用户的等级
            $status = $this->save(['grade_id' => $data['grade_id']]);
            // 新增用户等级修改记录
            if ($status) {
                (new GradeLogModel)->record([
                    'user_id' => $this['user_id'],
                    'old_grade_id' => $oldGradeId,
                    'new_grade_id' => $data['grade_id'],
                    'change_type' => ChangeTypeEnum::ADMIN_USER,
                    'remark' => $data['remark']
                ]);
            }
            return $status !== false;
        });
    }


    /**
     * 消减用户的实际消费金额
     * @param $userId
     * @param $expendMoney
     * @return int|true
     * @throws \think\Exception
     */
    public function setDecUserExpend($userId, $expendMoney)
    {
        return $this->where(['user_id' => $userId])->setDec('expend_money', $expendMoney);
    }


    /**
     * 是否为股东
     * @param $value
     * @return mixed
     */
    public function getShareholderAttr($value)
    {
        $status = [0 => '否', 1 => '是'];
        return ['text' => $status[$value], 'value' => $value];
    }


    /**
     * 修改商品状态
     * @param $state
     * @return false|int
     */
    public function setShareholder($state)
    {
        return $this->allowField(true)->save(['shareholder' => $state]) !== false;
    }

    /**
     * 修改用户分销权限1
     * @param $data
     * @return mixed
     */
    public function updateDeacler($data)
    {
        // 更新用户的等级
        $status = $this->save(['deacler' => $data['deacler']]);
        return $status !== false;
    }


    /**
     * 修改代言人身份
     * @param $data
     * @return mixed
     */
    public function updateStaff($data)
    {
        // 更新用户的等级
        $status = $this->save(['is_staff' => $data['staff']]);
        return $status !== false;
    }
}
